/**
 * 添加新阶段
 */
function addStage() {
    let courseTypeId = $('#type').find('option:selected').val();
    let title = $('#title').val().trim();
    let sort = $('#sort').val().trim();
    if(courseTypeId == '0'){
        swal("警告","请选择课程类别！", "warning");
        return;
    }else if (title == ''){
        swal("警告","名称不能为空！", "warning");
        return;
    }
    else if (sort == ''){
        swal("警告","排序不能为空！", "warning");
        return;
    }
    $.ajax({
        type: "POST",
        url: "addStage",
        data: {title:title,courseTypeId:courseTypeId,sort:sort},
        dataType: "json",
        success: function(data){
            if (data['code']== 200){
                swal("添加成功", "你已经成功创建了名称为《"+title+"》的课程阶段了", "success");
                setInterval(reload, 2000);
            }else if (data['code']== 501){
                swal("添加失败", "你已经创建过名称为《"+title+"》的课程阶段了，请换一个新名称吧~", "error");
            }else{
                swal("出错啦", "服务器发生了一个错误", "error");
            }
        }
    });
}

/**
 * 刷新页面
 */
function reload() {
    window.location.reload();
}

/**
 * 更新课程阶段
 */
function updateStage() {
    let courseTypeId = $('#type').find('option:selected').val();
    let title = $('#title').val().trim();
    let sort = $('#sort').val().trim();
    let id = $('#id').val().trim();
    if(courseTypeId == '0'){
        swal("警告","请选择课程类别！", "warning");
        return;
    }else if (title == ''){
        swal("警告","名称不能为空！", "warning");
        return;
    }else if (sort == ''){
        swal("警告","排序不能为空！", "warning");
        return;
    }
    $.ajax({
        type: "POST",
        url: "updateStage",
        data: {title:title,courseTypeId:courseTypeId,id:id,sort:sort},
        dataType: "json",
        success: function(data){
            if (data['code']== 200){
                swal("更新成功", "你已经成功更新了这个课程阶段", "success");
                setInterval(reload, 2000);
            }else if (data['code']== 501){
                swal("提示", "你没有修改任何信息", "info");
            }else if (data['code']== 502){
                swal("添加失败", "你已经创建过名称为《"+title+"》的标签了，请换一个新名称吧~", "error");
            }else{
                swal("出错啦", "服务器发生了一个错误", "error");
            }
        }
    });
}

/**
 * 删除课程阶段
 */
function deleteStage(id) {
    swal({
        title: "确定删除此课程阶段?",
        text: "删除此课程阶段之后，关联的课程不会一起删除！",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    })
        .then((willDelete) => {
            if (willDelete) {
                var location = window.location.href;
                let strings = location.split("iStudy");
                window.location.href = strings[0]+"iStudy/deleteStage?id="+id;
            }
        });
}